const util = require('../../utils/util')
let p

Page({

	data: {
		staticDomain: util.config('staticDomain'),
		activeTab: 0,
		activeCategoryId: '',
		storeInfo: null,
		goodsCategorys: [],
		goodsList: [],
		goodsSpec: {},
		goodsSpecPanelShow: false,
		shoppingBasketList: [],
		shoppingBasketShow: false,
		commentList: [],
		commentLoadEnd: false,
		goodsListTop: 0
	},

	temp: {
		storeId: '',
		tableNum: '',
		codeId: '',
		goodsData: [],
		status: {
			storeDataLoading: false,
			storeDataLoaded: false,
			commentLoading: false,
			commentLoaded: false
		}
	},

	onLoad: function (params) {
		p = this
		//热启动不带参数时返回主页
		if (!params.scene && !params.codeId && !params.storeId) {
			if (!util.globalData('pageParams')) {
				// wx.redirectTo({
				// 	url: '/pages/index/index',
				// })
				// return
				util.globalData('pageParams', { codeId: 'ed0oPyM0cIhWMIZxH9seCz0yD1lA2F4C' })
			}
			params = util.globalData('pageParams')
		}
		else
			util.globalData('pageParams', params)
		const { storeId, codeId, scene } = params
		p.getStoreData({
			storeId,
			codeId: scene || codeId,
			success: (data) => {
				p.loadStoreData({
					data,
					success: () => {
						
					},
					fail: () => {
						
					}
				})
			},
			fail: (code, msg) => {
				console.error(code, msg)
				if(code == '-2011') {
					util.showPanelErr({
						p, 
						icon: 'failed', 
						msg: '此商户已被冻结',
						use: '请返回上一层',
						title: '商户异常'
					})
				}
				else {
					util.showPanelErr({
						p,
						icon: 'failed',
						msg: `获取数据失败 ${code}`,
						use: '请下拉刷新重试'
					})
				}
			}
		})
	},

	onShow: () => {
		if (util.globalData('payedTemp'))
			p.clearShoppingBasket()
	},

	changeActiveTab: (e) => {
		if(!p.temp.status.storeDataLoaded) 
			return
		const tabIndex = e.currentTarget.dataset.index
		p.setData({ activeTab: tabIndex })
	},

	scrollTab: (e) => {
		if (!p.temp.status.storeDataLoaded)
			return
		const tabIndex = e.detail.current
		p.setData({
			activeTab: tabIndex
		})
		if (tabIndex == 1)
			p.loadComment(p.temp.storeId)
	},

	switchCategoryTab: (e) => {
		const categoryId = e.target.dataset.categoryid
		const { goodsData } = p.temp
		const goodsList = goodsData.filter((goods) => {
			return goods.goodsCategory == categoryId
		})
		p.setData({
			activeCategoryId: categoryId,
			goodsList,
			goodsListTop: 0
		})
	},

	chooseFoodSpec: (e) => {
		const goodsId = e.currentTarget.dataset.goodsid
		const { shoppingBasketList } = p.data
		let { goodsName, goodsChooseSpec, goodsSpec } = p.getMenuGoods(goodsId)
		for (let goods of shoppingBasketList)
			if (goods.goodsId == goodsId) {
				goodsChooseSpec = goods.chooseGoodsSpec
				break
			}
		p.setData({
			goodsSpec: {
				goodsId,
				goodsName,
				goodsChooseSpec,
				goodsSpecList: JSON.parse(goodsSpec)
			},
			goodsSpecPanelShow: true
		})
	},

	changeGoodsSpecChoose: (e) => {
		const goodsChooseSpec = e.currentTarget.dataset.choosegoodsspec
		const {goodsSpec} = p.data
		const { goodsId, goodsName, goodsSpecList } = goodsSpec
		p.setData({
			goodsSpec: {
				goodsId,
				goodsName,
				goodsChooseSpec,
				goodsSpecList
			}
		})
	},

	closeGoodsSpecPanel: () => {
		p.setData({
			goodsSpecPanelShow: false
		})
	},

	//添加菜品
	addGoods: (e) => {
		const goodsId = e.currentTarget.dataset.goodsid
		const goodsSpec = e.currentTarget.dataset.goodsspec
		p.shoppingBasketAdd(goodsId, goodsSpec)
	},

	//删除菜品
	delGoods: (e) => {
		const goodsId = e.currentTarget.dataset.goodsid
		const goodsSpec = e.currentTarget.dataset.goodsspec
		p.shoppingBasketDel(goodsId, goodsSpec)
	},

	//添加到购物车
	shoppingBasketAdd: (goodsId, chooseGoodsSpec) => {
		let { shoppingBasketList } = p.data
		const { goodsName, goodsCategory, goodsSpec } = p.getMenuGoods(goodsId)
		if (shoppingBasketList.length == 0) {
			const { goodsPrice, goodsSpecName, goodsSpecPrice } = p.getGoodsSpec(goodsSpec, chooseGoodsSpec)
			shoppingBasketList.push({
				goodsId,
				goodsCategory,
				goodsName,
				chooseGoodsSpec,
				goodsSpecName,
				goodsCount: 1,
				goodsPrice: goodsPrice || goodsSpecPrice
			})
		}
		else {
			for (let i in shoppingBasketList) {
				let goods = shoppingBasketList[i]
				if (goods.goodsId == goodsId && goods.goodsCount < 99 && goods.chooseGoodsSpec == chooseGoodsSpec) {
					goods.goodsCount++
					break
				}
				else if (i == shoppingBasketList.length - 1) {
					const { goodsPrice, goodsSpecName, goodsSpecPrice } = p.getGoodsSpec(goodsSpec, chooseGoodsSpec)
					shoppingBasketList.push({
						goodsId,
						goodsCategory,
						goodsName,
						chooseGoodsSpec,
						goodsSpecName,
						goodsCount: 1,
						goodsPrice: goodsPrice || goodsSpecPrice
					})
				}
			}
		}
		p.setData({
			shoppingBasketList
		})
	},

	//从购物车移除
	shoppingBasketDel: (goodsId, chooseGoodsSpec) => {
		let { shoppingBasketList } = p.data
		const { goodsName, goodsSpec } = p.getMenuGoods(goodsId)
		for (let i in shoppingBasketList) {
			let goods = shoppingBasketList[i]
			if (goods.goodsCount == 1) {
				shoppingBasketList.splice(i, 1)
				break
			}
			else if (goods.goodsId == goodsId && goods.chooseGoodsSpec == chooseGoodsSpec) {
				goods.goodsCount--
				break
			}
		}
		p.setData({
			shoppingBasketList
		})
	},

	showShoppingBasket: () => {
		p.setData({
			shoppingBasketShow: !p.data.shoppingBasketShow,
			goodsSpecPanelShow: false
		})
	},

	clearShoppingBasket: () => {
		p.setData({
			shoppingBasketList: [],
			shoppingBasketShow: false
		})
	},

	callStorePhone: () => {
		const { storePhone } = p.data.storeInfo
		wx.makePhoneCall({
			phoneNumber: storePhone,
			fail: () => {
				wx.setClipboardData({
					data: storePhone,
					success: () => {
						util.error('无法拨打', '非常抱歉我们无法调用您的通话设备，已将此电话号码复制到您的剪贴板，您可以复制到拨号的号码输入框拨打')
					},
					fail: () => {
						util.error('无法拨打', '非常抱歉我们无法调用您的通话设备，无法拨打电话')
					}
				})
			}
		})
	},

	//检查是否登录未登录将执行登录
	checkLogin: (callback) => {
		const { success, fail } = callback
		if (util.globalData('logined')) {
			success(util.globalData('userData'))
			return
		}
		util.startLogin({
			success,
			fail
		})
	},

	buyOrder: () => {
		const { storeInfo, shoppingBasketList } = p.data
		const { goodsData } = p.temp
		const { tableNum } = p.temp
		if (shoppingBasketList.length == 0)
			return
		p.checkLogin({
			success: (userData) => {
				if (!tableNum) {
					util.iconBox('/images/scanCode', '请扫描桌码')
					setTimeout(() => {
						p.scanGtCode()
					}, 600)
				}
				else {
					console.log(userData)
					util.globalData('orderDataTemp', {
						storeId: storeInfo.storeId,
						storeName: storeInfo.storeName,
						storePayMode: storeInfo.storePayMode,
						tableNum,
						orderGoodsList: shoppingBasketList,
						orderAttachList: goodsData.filter((goods) => {
							if (goods.goodsCategory == 'attach' || goods.goodsCategory == 'must') {
								return true
							}
						})
					})
					util.goPage('pay')
				}
			},
			fail: (title, err) => {
				util.error(title, err)
			}
		})
	},

	//扫描粿团二维码
	scanGtCode: () => {
		wx.scanCode({
			success: (res) => {
				console.log(res)
				let codeId = ''
				try {
					codeId = res.path.split('?')[1].split('=')[1]
					if (codeId.length != 32) {
						throw ('非粿团二维码')
					}
				}
				catch (err) {
					console.error(err)
					wx.showModal({
						title: '可能扫了假二维码',
						content: '亲可能扫错二维码了哟，请扫描桌面上的粿团小程序二维码噢',
						showCancel: false
					})
					return
				}
				console.log(codeId)
				p.getTableNum({
					codeId,
					success: (tableNum) => {
						p.temp.tableNum = tableNum
						p.buyOrder()
					},
					fail: (title, msg, callback) => {
						util.error(title, msg, callback)
					}
				})
			},
			fail: (err) => {
				if (err.errMsg.indexOf('cancel') == -1) {
					util.error('扫码失败', '请重新扫描二维码')
				}
				else {
					wx.showModal({
						title: '提示',
						content: '需要扫码提交订单噢',
						showCancel: false
					})
				}
			}
		})
	},

	getMenuGoods: (goodsId) => {
		const { goodsList } = p.data
		const { goodsData } = p.temp
		let goods = goodsList.filter((goods) => {
			return goods.goodsId == goodsId
		})
		if(!goods[0])
			goods = goodsData.filter((goods) => {
				return goods.goodsId == goodsId
			})
		return goods[0]
	},

	getGoodsSpec: (goodsSpec, chooseGoodsSpec) => {
		if(!isNaN(goodsSpec))
			return { goodsPrice: parseInt(goodsSpec) }
		const temp = JSON.parse(goodsSpec)
		const {n,p} = temp[chooseGoodsSpec]
		return {
			goodsSpecName: n,
			goodsSpecPrice: parseInt(p)
		}
	},

	getStoreData: (obj) => {
		const { storeId, codeId, success, fail } = obj
		//临时存放codeId供加载其它使用
		p.temp.codeId = codeId
		if ((!codeId && !storeId) || (codeId && !p.checkCodeId(codeId)) || (storeId && !p.checkStoreId(storeId))) {
			util.showPanelErr({
				p,
				icon: 'failed',
				msg: `数据错误`,
				use: '请返回上一层'
			})
			return
		}
		const { storeDataLoading, storeDataLoaded } = p.temp.status
		if (storeDataLoading || storeDataLoaded)
			return
		wx.showNavigationBarLoading()
		p.temp.status.storeDataLoading = true
		util.request({
			method: 'get',
			uri: `store/${codeId || storeId}`,
			sign: false,
			success: (data) => {
				//临时存放storeId供加载其它使用
				p.temp.storeId = data.storeId || storeId
				success(data)
			},
			fail: (code, msg) => {
				wx.hideNavigationBarLoading()
				wx.stopPullDownRefresh()
				p.temp.status.storeDataLoading = false
				fail(code, msg)
			}
		})
	},

	getCommentData: (obj) => {
		const { storeId, index = 0, count = 20, success, fail } = obj
		p.temp.status.commentLoading = true
		util.showLoadingBox(p)
		util.request({
			method: 'get',
			uri: `store/${storeId}/comment`,
			data: {
				index,
				count
			},
			sign: false,
			success: (data) => {
				if(data.length == 0) {
					p.temp.status.commentLoading = false
					p.temp.status.commentLoaded = true
					util.hideLoadingBox(p)
					p.setData({
						commentLoadEnd: true
					})
				}
				else
					success(data)
			},
			fail: (code, msg) => {
				util.hideLoadingBox(p)
				p.temp.status.commentLoading = false
				fail(code, msg)
			}
		})
	},

	//根据粿团二维码ID获取桌号
	getTableNum: (callback) => {
		util.loading('请稍后')
		let { codeId, success, fail } = callback
		util.request({
			method: 'get',
			uri: `store/${codeId}/tableNum`,
			sign: false,
			success: (data) => {
				wx.hideToast()
				const {storeId, tableNum} = data
				if (storeId != p.temp.storeId) {
					wx.showModal({
						title: '非此店桌码',
						content: '您所扫的桌码不是您所在的店铺的桌码噢，请重新扫码噢',
						showCancel: false
					})
				}
				else
					success(tableNum)
			},
			fail: (code, msg) => {
				wx.hideToast()
				if (code == '-2016') {
					fail('桌码有误', '非常抱歉，此桌码出错了哦')
				}
				else if(code == '-2018') {
					fail('桌码有误', '非常抱歉，此桌码尚未激活哦')
				}
				else
					fail('获取桌号失败', '获取桌号失败啦，请君重新扫过噢(╥╯^╰╥)')
			}
		})
	},

	loadStoreData: (obj) => {
		try {
			const { data, success, fail } = obj
			const { store, menu, coupon, tableNum } = data
			const { storeName } = store
			const { category } = menu
			wx.setNavigationBarTitle({
				title: tableNum ? `${storeName} | ${tableNum}` : storeName
			})
			p.temp.tableNum = tableNum
			if (category.length == 0) 
				return
			//临时存储所有菜品数据
			p.temp.goodsData = menu.goods
			const goodsList = menu.goods.filter((goods) => {
				return goods.goodsCategory == category[0].categoryId
			})
			p.setData({
				storeInfo: store,
				goodsCategorys: category,
				goodsList,
				activeCategoryId: category[0].categoryId
			})
			util.hidePanelErr(p)
			p.temp.status.storeDataLoaded = true
			success()
		}
		catch(err) {
			console.error(err)
			fail('-1', 'load store data failed')
		}
		p.temp.status.storeDataLoading = false
		wx.stopPullDownRefresh()
		wx.hideNavigationBarLoading()
	},

	loadCommentData: (obj) => {
		const { data, success, fail } = obj
		try {
			const { commentList } = p.data
			p.setData({
				commentList: commentList.concat(data)
			})
		}
		catch(err) {
			console.error(err)
			fail('-1', 'load comment data failed')
		}
		util.hideLoadingBox(p)
		p.temp.status.commentLoading = false
	},

	loadComment: (storeId) => {
		const { commentList } = p.data
		const {commentLoading, commentLoaded} = p.temp.status
		if (commentLoading || commentLoaded)
			return
		p.getCommentData({
			storeId,
			index: commentList.length,
			count: 5,
			success: (data) => {
				p.loadCommentData({
					data,
					success: () => {

					},
					fail: (code, msg) => {
						console.error(code, msg)
						util.tip({
							p,
							text: `加载评论失败 ${code}`
						})
					}
				})
			},
			fail: (code, msg) => {
				console.error(code, msg)
				util.tip({
					p,
					text: `获取评论失败 ${code}`
				})
			}
		})
	},

	loadMoreComment: () => {
		p.loadComment(p.temp.storeId)
	},

	checkStoreId: (storeId) => {
		if (!storeId)
			return
		return /^[a-zA-Z0-9]{10}$/.test(storeId)
	},

	checkCodeId: (codeId) => {
		if (!codeId)
			return
		return /^[a-zA-Z0-9]{32}$/.test(codeId)
	},

	emptyTap: () => {},

	onPullDownRefresh: () => {
		const { activeTab } = p.data
		const { storeId } = p.temp
		if (activeTab == 0) {
			const { storeId, codeId, status } = p.temp
			if (!status.storeDataLoading && !status.storeDataLoaded)
				if (codeId)
					p.onLoad({ codeId })
				else
					p.onLoad({ storeId })
			else
				wx.stopPullDownRefresh()
		}
		else
			wx.stopPullDownRefresh()
	},

	// onShareAppMessage: () => {
	// 	const { staticDomain, storeInfo } = p.data
	// 	let { storeId, storeName } = storeInfo
	// 	return {
	// 		title: `${storeName}-粿团点餐`,
	// 		path: `/pages/store/store?codeId=${storeId}`,
	// 		imageUrl: `${staticDomain}image/store/${storeId}/cover`
	// 	}
	// }

})